package com.halko.PR.controller;

import com.halko.PR.pojo.Result;
import com.halko.PR.service.PlateRecognise;
import com.halko.PR.service.impl.PlateRecogniseImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author halko
 * @create 2021-04-11 19:06
 */
@RestController
public class PlateRecogniseController {


    @Autowired
    PlateRecognise plateRecognise;

    /**
     * 车牌识别
     * @param file
     * @return
     */
    @PostMapping(value = "/api/plateRecognise")
    @ResponseBody
    public Result plateRecognise(@RequestParam("file") MultipartFile file){
        if (file.isEmpty() || file == null){
            List<String> responses = new ArrayList<String>();
            responses.add("文件为空");
            return new Result(-1,responses,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        }
        String fileName = file.getOriginalFilename();
        @SuppressWarnings("unused")
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "D:\\image\\";
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            String img = filePath + fileName;
            List<String> res = plateRecognise.plateRecognise(img);
            if (res.size() < 1 || res.contains("")){
                List<String> responses = new ArrayList<String>();
                responses.add("识别不了");
                return new Result(-1,responses,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

            }
            Result result = new Result(201,plateRecognise.plateRecognise(img),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<String> responses = new ArrayList<String>();
        responses.add("上传失败");
        return new Result(-1,responses,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
}
